from google.appengine.ext import db
from google.appengine.api import urlfetch


# App Configuration
class AppConfig(db.Model):
    param_key = db.StringProperty()
    param_val = db.StringProperty()


# get parameter's value
def get_param(key):
    query = db.GqlQuery("SELECT * FROM AppConfig where param_key = :1", key)
    result = query.get()
    if result != None:
        return result.param_val
    else:
        return None


# set parametter's value 
def set_param(key, val):
    query = db.GqlQuery("SELECT * FROM AppConfig where param_key = :1", key)
    result = query.get()
    if result != None:
        result.delete()
    cfg = AppConfig(param_key=key, param_val=val)
    cfg.save()


# get all paraemters
def get_all():
    query = AppConfig.all()
    results = query.fetch(20)
    params = dict()
    for result in results:
        params[result.param_key] = result.param_val

    # initialize at first time
    if "twitter_username" not in params:
        params["twitter_username"] = "username"
    if "twitter_password" not in params:
        params["twitter_password"] = "password"
    if "twitter_url" not in params:
        params["twitter_url"] = "http://twitter.com/statuses/user_timeline/username.json"
    if "twitter_since_id" not in params:
        params["twitter_since_id"] = "0"
    if "minicloud_username" not in params:
        params["minicloud_username"] = "username"
    if "minicloud_password" not in params:
        params["minicloud_password"] = "password"
    if "minicloud_url" not in params:
        params["minicloud_url"] = "http://api.minicloud.com.cn/statuses/update.json"
    return params


# set all parameters
def set_all(params):
    for key in params.keys():
        set_param(key, params[key])


# clear tweet log
def clear():
    query = db.GqlQuery("SELECT * FROM AppConfig")
    results = query.fetch(20)
    for result in results:
        result.delete()
